package admin

import (
	"fmt"
	"gitee.com/chejiangyi/bsfgo/core/utils"
	"gitee.com/chejiangyi/bsfgo/demo/service/dals"
	"gitee.com/chejiangyi/bsfgo/demo/web/controller/base"
	"gitee.com/chejiangyi/bsfgo/gin2/session2"
	"github.com/gin-gonic/gin"
)

type HomeController struct {
	base.BaseAdminWebController
}

func (m *HomeController) Index(c *gin.Context) {
	defer m.CatchHtmlError(c)
	m.Html(c, "home/index.html", gin.H{})
}

func (m *HomeController) Error(c *gin.Context) {
	if err := recover(); err != nil {
		utils.LogUtil.Error2(fmt.Sprintf("严重错误,错误页出错:%v", err))
	}
	m.CheckUserAuth(c)
	err, _ := c.Get("error")
	m.Html(c, "home/error.html", gin.H{"error": err})
}

func (m *HomeController) Login(c *gin.Context) {
	defer m.CatchJsonError(c)
	username := c.PostForm("username")
	password := c.PostForm("password")
	user := dals.DbUserDal.Login(m.GetConn(), username, password)
	if user == nil {
		m.JsonError(c, "账号或密码错误")
	} else {
		session2.SessionUtil.GetSessionDefault(c).Set("user",
			base.SessionUser{UserId: user.Id, UserName: user.Name, IsAdmin: true},
		).Save()
		m.JsonSuccess(c, gin.H{})
	}
}

func (m *HomeController) LoginOut(c *gin.Context) {
	defer m.CatchJsonError(c)
	session2.SessionUtil.GetSessionDefault(c).Delete("user")
	m.JsonSuccess(c, gin.H{})
}
